package com.lanou3g.code0416;

import java.io.*;

/**
 * Created by dllo on 18/4/16.
 */
public class Test03 {
    public static void main(String[] args) {
        read();
        write();

    }

    public static void write() {
        File file = new File("test.txt");
        //Bufferedwriter 还是不方便
        //写文本的时候,通常使用PrintWriter
        PrintWriter pw = null;
        OutputStreamWriter osw = null;
        FileOutputStream fos = null;
        try {
            //是否是追加模式
            //再加一个true参数,就是追加模式
            fos = new FileOutputStream(file,true);
            osw = new OutputStreamWriter(fos);
            pw = new PrintWriter(osw);

            //写入文件的时候
            //用法跟System.out一样
            pw.println(1);
            pw.println("窗前明月光");
            pw.println(3.14);
            pw.print("荆轲刺秦王");
            pw.print("哈哈");

            pw.flush();
            //写完之后,务必加上flush
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeAll(pw);
        }
    }

    //使用字符流读取文本信息
    public static void read() {
        File file = new File("test.txt");
        BufferedReader reader = null;
        InputStreamReader isr = null;
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            reader = new BufferedReader(isr);
            String line = "";
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {//readLine读一行,一直读到换行
                //如果最后的结果想要保留换行信息,
                //则需要手动拼接换行,大多数情况下,都不需要
                sb.append(line).append("\n");
                System.out.println("->" + line);
            }
            String result = sb.toString();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeAll(reader);
        }

    }
}
